package com.example.aloy.fragment.first


import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.annotation.ColorInt
import androidx.annotation.RequiresApi
import androidx.viewbinding.ViewBinding
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.example.aloy.activity.BasicActivity
import com.example.aloy.activity.BottomNavActivity
import com.example.aloy.databinding.FragmentTopNavBinding
import com.example.aloy.fragment.BasicFragment
import com.example.aloy.fragment.second.BannerFragment
import com.google.android.material.tabs.TabLayoutMediator


abstract class TopNavFragment : BasicFragment() {
    private lateinit var tabTitleList: Array<String>
    private lateinit var tabFragmentList: ArrayList<BannerFragment>

    private lateinit var mainViewPager: ViewPager2

    abstract fun getTabTitleList(): Array<String>

    abstract fun getTabFragmentList(): ArrayList<BannerFragment>

    override fun onBindingView(): ViewBinding {
        return FragmentTopNavBinding.inflate(layoutInflater)
    }

    override fun isInterceptEvent(): Boolean {
        return true
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        tabTitleList = getTabTitleList()
        tabFragmentList = getTabFragmentList()
        setPrimaryColorListener(object : OnPrimaryColorListener {
            override fun onPrimaryColorChanged(primaryColorInt: Int) {
                setTabLayoutBackgroundColor(primaryColorInt)
            }
        })
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewPager()
        setPrimaryColor(0)
    }

    private fun setTabLayoutBackgroundColor(@ColorInt colorInt: Int) {
        (binding as FragmentTopNavBinding).tabLayout.setBackgroundColor(colorInt)
    }

    fun setTabLayoutTextColors(@ColorInt colorInt: Int, @ColorInt selectedColorInt: Int) {
        (binding as FragmentTopNavBinding).tabLayout.setTabTextColors(colorInt, selectedColorInt)
    }

    private fun setPrimaryColor(position: Int) {
        val backgroundColor = tabFragmentList[position].backgroundColor

        setTabLayoutTextColors(
            tabFragmentList[position].textColor,
            tabFragmentList[position].textSelectedColor
        )

        setTabLayoutBackgroundColor(backgroundColor)

        //设置activity的主题色
        if (activity is BasicActivity) {
            (activity as BasicActivity).setStatusBarColor(backgroundColor)
            (activity as BasicActivity).setActionBarColor(backgroundColor)
        }
    }

    private fun initViewPager() {
        mainViewPager = (activity as BottomNavActivity).getMainViewPager()
        (binding as FragmentTopNavBinding).childViewPager.offscreenPageLimit = 1
        (binding as FragmentTopNavBinding).childViewPager.adapter =
            object : FragmentStateAdapter(this) {
                override fun createFragment(position: Int) = tabFragmentList[position]

                override fun getItemCount() = tabTitleList.size
            }
        TabLayoutMediator(
            (binding as FragmentTopNavBinding).tabLayout,
            (binding as FragmentTopNavBinding).childViewPager
        ) { tab, position ->
            tab.text = tabTitleList[position]
        }.attach()

        (binding as FragmentTopNavBinding).childViewPager.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            private var currentPosition = 0     //当前滑动位置
            private var oldPosition = 0          //上一个滑动位置
            private var currentState = 0
            private var scrolledPixelList = mutableListOf<Int>() //记录手指滑动时的像素坐标记录

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                setPrimaryColor(position)
            }

            //决定要不要把滑动事件交给父ViewPager处理
            override fun onPageScrollStateChanged(state: Int) {
                currentState = state
                Log.d("TAG1", "onPageScrollStateChanged $state")

                // 所有交互事件结束的状态，值为0
                if (state == ViewPager2.SCROLL_STATE_IDLE) {
                    if (currentPosition == oldPosition) {
                        when (currentPosition) {
                            0 -> {
                                Log.d("TAG1", "到达最左一个继续往左滑....")
                                //若还有上一个bottom fragment页面则切换
                                mainViewPager.currentItem.takeIf { it > 0 }
                                    ?.also { (activity as BottomNavActivity).switchFragment(it - 1) }
                            }

                            ((binding as FragmentTopNavBinding).childViewPager.adapter as FragmentStateAdapter).itemCount - 1 -> {
                                if (scrolledPixelList.size > 1 && scrolledPixelList.last() - scrolledPixelList[0] < 0) {
                                    //有可能出现向左滑到一点放弃的情况也是可以出现currentPosition == oldPosition，则先判断是否是往左滑时放弃
                                    return
                                }
                                Log.d("TAG1", "到达最右一个继续往右滑....")
                                //若还有下一个bottom fragment页面则切换
                                mainViewPager.currentItem.takeIf { it < mainViewPager.adapter!!.itemCount - 1 }
                                    ?.also { (activity as BottomNavActivity).switchFragment(it + 1) }
                            }
                        }
                    }
                    oldPosition = currentPosition
                    scrolledPixelList.clear()//清空滑动记录
                }
            }

            //页面滚动的位置信息回调： position 当前滚动到哪个页面，positionOffset 位置偏移百分比, positionOffsetPixels 当前所在页面偏移量
            //此回调会触发完onPageScrollStateChanged 的 state 值为1时后面才触发回调
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                currentPosition = position
                if (currentState == ViewPager2.SCROLL_STATE_DRAGGING) {
                    //手指按下滑动状态,值为1
                    scrolledPixelList.add(positionOffsetPixels)
                }
            }
        })
    }
}
